﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Drawing;
using GreatB2C.Utility;

namespace GreatB2C.Web.Manage.SystemSet.Contents
{
    public partial class FieldManage : Inherit.ManagePage
    {
        Business.Model BLL = new Business.Model( );

        protected void Page_Load( object sender , EventArgs e )
        {
            if ( !IsPostBack )
            {
                if ( Request.QueryString[ "ModelType" ] != null && Request.QueryString[ "ModelType" ].ToString( ) != ""
                    && Request.QueryString[ "ModelID" ] != null && Request.QueryString[ "ModelID" ].ToString( ) != "" )
                {
                    LoadData( );
                }
                else
                {
                    litScript.Text = "<script type='text/javascript'>ShowInfoAndRedirect('错误','非法进入页面或参数传入错误！','ModelManage.aspx');</script>";
                }
            }
        }

        private void LoadData( )
        {
            // 根据数据库对应的表，映射到相应的操作对象
            if ( Request.QueryString[ "ModelType" ] != null && Request.QueryString[ "ModelType" ].ToString( ) != ""
                    && Request.QueryString[ "ModelID" ] != null && Request.QueryString[ "ModelID" ].ToString( ) != "" )
            {
                DataTable dtData = null;
                Component.DefaultTemplateFields defaultFields = new GreatB2C.Web.Component.DefaultTemplateFields( );
                string type = Request.QueryString[ "ModelType" ].ToString( );
                int id = Convert.ToInt32( Request.QueryString[ "ModelID" ].ToString( ) );

                if ( ViewState[ "data" ] == null )
                {
                    // 从模板传入
                    if ( type == "1" )
                    {
                        GreatB2C.Model.Model modelModel = new GreatB2C.Model.Model( );
                        modelModel.ModelID = id;
                        Business.Model modelBLL = new GreatB2C.Business.Model( );
                        modelModel = modelBLL.ListByID( modelModel );
                        if ( modelModel != null )
                        {
                            defaultFields.Field = modelModel.Field;
                            dtData = defaultFields.GetDataTable( "" ); ;
                        }
                    }
                    else if ( type == "2" )     // 从模型模板传入
                    {
                        GreatB2C.Model.ModelTemplates modelTemplate = new GreatB2C.Model.ModelTemplates( );
                        modelTemplate.TemplateID = id;
                        Business.ModelTemplates templateBLL = new GreatB2C.Business.ModelTemplates( );
                        modelTemplate = templateBLL.ListByID( modelTemplate );
                        if ( modelTemplate != null )
                        {
                            defaultFields.Field = modelTemplate.Field;
                            dtData = defaultFields.GetDataTable( "" );
                        }
                    }

                    ViewState[ "data" ] = dtData;
                }
                else
                {
                    dtData = ( DataTable )ViewState[ "data" ];
                }

                DataView dvData = dtData.DefaultView;
                dvData.Sort = "OrderID asc";

                if ( dvData.Count > 0 )
                {
                    count = dvData.Count;
                    dgData.DataSource = dvData;
                    dgData.DataBind( );

                    dgData.Visible = true;
                    litNone.Visible = false;
                }
                else
                {
                    dgData.Visible = false;
                    litNone.Text = "<div style='width:120px; margin:0 auto; margin-top:20px;'>没 有 任 何 数 据 ！</div>";
                }
            }
        }

        protected void AspNetPager1_PageChanged( object src , EventArgs e )
        {
            LoadData( );
        }

        int count = 0;
        protected void dgData_ItemDataBound( object sender , DataGridItemEventArgs e )
        {
            if ( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
            {
                //添加自定义属性，当鼠标移过来时设置该行的背景色,并保存原背景色
                e.Item.Attributes.Add( "onmouseover" , "this.className='tdbgmouseover';" );
                //添加自定义属性，当鼠标移走时还原该行的背景色
                e.Item.Attributes.Add( "onmouseout" , "this.className='tdbg';" );
                //添加双击事件
                e.Item.Attributes.Add( "ondblclick" , "RowDblclick('ModelModify.aspx?Action=Modify&ModelID=" + e.Item.Cells[ 1 ].Text.Trim( ) + "');" );

                if ( e.Item.Cells[ 4 ].Text.Trim( ) == "0" )
                {
                    e.Item.Cells[ 1 ].ForeColor = Color.Red;
                    e.Item.Cells[ 4 ].Text = "系统";
                    e.Item.Cells[ 4 ].ForeColor = Color.Green;
                }
                else
                {
                    e.Item.Cells[ 4 ].Text = "自定义";
                }

                if ( e.Item.Cells[ 5 ].Text.Trim( ).ToLower( ) == "true" )
                {
                    e.Item.Cells[ 5 ].Text = "√";
                }
                else
                {
                    e.Item.Cells[ 5 ].Text = "×";
                    e.Item.Cells[ 5 ].ForeColor = Color.Red;
                }

                if ( e.Item.Cells[ 6 ].Text.Trim( ).ToLower( ) == "true" )
                {
                    e.Item.Cells[ 6 ].Text = "√";
                }
                else
                {
                    e.Item.Cells[ 6 ].Text = "×";
                    e.Item.Cells[ 6 ].ForeColor = Color.Red;
                }

                DropDownList ddlOrderId = ( DropDownList )e.Item.FindControl( "ddlOrderId" );
                for ( int i=0 ; i < count ; i++ )
                {
                    ddlOrderId.Items.Add( new ListItem( ( i + 1 ).ToString( ) ) );
                }

                ddlOrderId.SelectedValue = e.Item.Cells[ 8 ].Text.Trim( );
            }
        }

        protected void dgData_ItemCommand( object source , DataGridCommandEventArgs e )
        {
            bool isSuccess = false;
            string name = e.Item.Cells[ 3 ].Text.Trim( );
            string id = e.CommandArgument.ToString( );
            if ( id.Trim( ) != "" )
            {
                switch ( e.CommandName )
                {
                    case "ListFields":

                        break;
                    case "Forbidden":
                        bool disabled = true;
                        LinkButton lbtnForbidden = ( LinkButton )e.Item.FindControl( "lbtnForbidden" );
                        if ( e.Item.Cells[ 7 ].Text.Trim( ).ToLower( ) == "true" )
                        {
                            disabled = false;
                        }
                        isSuccess = BLL.UpdateModelStatus( Convert.ToInt32( id ) , disabled );
                        if ( isSuccess )
                        {
                            LoadData( );
                        }
                        else
                        {
                            litScript.Text = "<script type='text/javascript'>ShowError('操作失败','内容模型信息" + lbtnForbidden.Text + "失败！');</script>";
                        }
                        break;
                    case "Delete":
                        GreatB2C.Model.Model model = new GreatB2C.Model.Model( );
                        model.ModelID = Convert.ToInt32( id );
                        isSuccess = BLL.Delete( model );
                        if ( isSuccess )
                        {
                            litScript.Text = "<script type='text/javascript'>ShowInfoAndRedirect('操作成功','内容模型信息（" + name + "）删除成功！','ModelManage.aspx');</script>";
                        }
                        else
                        {
                            litScript.Text = "<script type='text/javascript'>ShowError('操作失败','内容模型信息（" + name + "）删除失败！');</script>";
                        }
                        break;
                    case "SaveAsModel":
                        Response.Redirect( "ModelTemplate.aspx?Action=AddModelToFieldTemplate&ModelID=" + id );
                        break;
                }
            }
        }

        protected void btnSaveFields_Click( object sender , EventArgs e )
        {
            if ( ViewState[ "data" ] != null )
            {
                DataTable dtData = ( DataTable )ViewState[ "data" ];
                Component.DefaultTemplateFields dtf = new GreatB2C.Web.Component.DefaultTemplateFields( );
                foreach ( DataRow dr in dtData.Rows )
                {
                    dtf.AddRow( dr );
                }

                string fields = dtf.GetXMLData( );
                if ( fields.Trim( ) != "" )
                {
                    bool isSuccess = BLL.UpdateModelFieldInfo( Convert.ToInt32( Request.QueryString[ "ModelID" ].ToString( ) ) , fields );
                    if ( isSuccess )
                    {
                        litScript.Text = "<script type='text/javascript'>ShowInfo('操作成功','模型字段排序信息保存成功！');</script>";
                    }
                    else
                    {
                        litScript.Text = "<script type='text/javascript'>ShowError('操作失败','模型字段排序信息保存失败！');</script>";
                    }
                }
            }
        }

        protected void ddlOrderId_SelectedIndexChanged( object sender , EventArgs e )
        {
            DropDownList ddlOrder = ( DropDownList )sender;
            int src_id = Convert.ToInt32( ddlOrder.ToolTip.ToString( ).Trim( ) );
            int des_id = Convert.ToInt32( ddlOrder.SelectedValue );

            if ( ViewState[ "data" ] != null )
            {
                DataTable dtData = ( DataTable )ViewState[ "data" ];
                int min = des_id < src_id ? des_id : src_id;
                int max = src_id > des_id ? src_id : des_id;

                if ( src_id > des_id )
                {
                    // 靠前排
                    int change_idx = -1;

                    for ( int i=0 ; i < dtData.Rows.Count ; i++ )
                    {
                        int cur = Convert.ToInt32( dtData.Rows[ i ][ "OrderID" ].ToString( ) );

                        if ( cur == src_id )
                        {
                            change_idx = i;
                            continue;
                        }
                        else if ( cur >= des_id && cur < src_id )
                        {
                            dtData.Rows[ i ][ "OrderID" ] = cur + 1;
                        }
                    }

                    if ( change_idx > -1 )
                        dtData.Rows[ change_idx ][ "OrderID" ] = des_id;

                    ViewState[ "data" ] = dtData;
                    LoadData( );
                }
                else
                {
                    // 靠后排
                    int change_idx = -1;

                    for ( int i=0 ; i < dtData.Rows.Count ; i++ )
                    {
                        int cur = Convert.ToInt32( dtData.Rows[ i ][ "OrderID" ].ToString( ) );

                        if ( cur == src_id )
                        {
                            change_idx = i;
                            continue;
                        }
                        else if ( cur > src_id && cur <= des_id )
                        {
                            dtData.Rows[ i ][ "OrderID" ] = cur - 1;
                        }
                    }

                    if ( change_idx > -1 )
                        dtData.Rows[ change_idx ][ "OrderID" ] = des_id;

                    ViewState[ "data" ] = dtData;
                    LoadData( );
                }
            }
        }


    }
}
